package com.sk.cardeal.act.home.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dyhdyh.widget.loading.dialog.LoadingDialog;
import com.flipboard.bottomsheet.BottomSheetLayout;
import com.sk.cardeal.R;
import com.sk.cardeal.adapter.IndicatorExpandableListAdapter;
import com.sk.cardeal.adapter.PartsKindAdapter;
import com.sk.cardeal.base.BaseActivity;
import com.sk.cardeal.callback.CountCallback;
import com.sk.cardeal.callback.HandleDataCallBack;
import com.sk.cardeal.dialog.BottomDataFragment;
import com.sk.cardeal.entity.KindList;
import com.sk.cardeal.entity.NewPartsList;
import com.sk.cardeal.entity.NewPartsParam;
import com.sk.cardeal.entity.Parts;
import com.sk.cardeal.utils.AppApi;
import com.sk.cardeal.utils.MyUtils;
import com.sk.cardeal.view.CustomPopWindow;
import com.sk.cardeal.view.FlowLayout;
import com.sk.cardeal.view.MultiStateView;
import com.sk.cardeal.view.SimpleMultiStateView;
import com.sk.cardeal.view.TitleView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by sk on 2018/3/16.
 */


public class NewChoosePartsActivity extends BaseActivity implements HandleDataCallBack, CountCallback, CompoundButton.OnCheckedChangeListener {
    @BindView(R.id.title_view)
    TitleView titleView;
    @BindView(R.id.ed_search)
    EditText edSearch;
    @BindView(R.id.data_list)
    ExpandableListView dataList;
    @BindView(R.id.SimpleMultiStateView)
    SimpleMultiStateView simpleMultiStateView;
    @BindView(R.id.tv_tip)
    TextView tvTip;
    @BindView(R.id.sure)
    TextView sure;
    @BindView(R.id.bottomsheet)
    BottomSheetLayout bottomsheet;
    @BindView(R.id.tv_filter)
    TextView tvFilter;
    @BindView(R.id.select_ll)
    RecyclerView selectLl;
    @BindView(R.id.dl_layout)
    DrawerLayout dlLayout;
    @BindView(R.id.pos_ryc)
    RecyclerView posRyc;
    @BindView(R.id.p_ryc)
    RecyclerView pRyc;
    @BindView(R.id.c_ryc)
    RecyclerView cRyc;
    @BindView(R.id.pos_radio)
    RadioButton posRadio;
    @BindView(R.id.function_radio)
    RadioButton functionRadio;
    private LoadingDialog loadingDialog;

    private String id;
    private NewPartsParam newPartsParam;
    private String searching = "";
    private int page = 0;
    private ArrayList<NewPartsList.ResultListBean> allDataList = new ArrayList<>();
    private int count = 0;
    private ArrayList<NewPartsList.ResultListBean.PartsQualityListBean> selectList = new ArrayList<>();
    private IndicatorExpandableListAdapter adapter;
    CustomPopWindow popWindow;
    private BottomDataFragment bottomDataFragment;

    private List<KindList.ResultListBean> posList = new ArrayList<>();
    private List<KindList.ResultListBean> pList = new ArrayList<>();
    private List<KindList.ResultListBean> cList = new ArrayList<>();

    private PartsKindAdapter selectAdapter;
    private PartsKindAdapter posAdapter;
    private PartsKindAdapter pAdapter;
    private PartsKindAdapter cAdapter;

    private String typeId;
    private String vin;

    @Override
    protected int getContentView() {
        return R.layout.activity_new_choose_parts;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        List<NewPartsList.ResultListBean.PartsQualityListBean> getDataList = new ArrayList<>();
        getDataList = getIntent().getParcelableArrayListExtra("data");
        posRadio.setChecked(true);

        posRadio.setOnCheckedChangeListener(this);
        functionRadio.setOnCheckedChangeListener(this);

        selectList.addAll(getDataList);

        if (selectList.size() > 0) {
            int count = 0;
            for (NewPartsList.ResultListBean.PartsQualityListBean entity : selectList) {
                count += entity.getWantCount();
            }
            tvTip.setText("已选择" + count + "件");
        }

        initRyc();

        initStateView();
        initSearch();
        titleView.setMyCallBack(this);
        id = getIntent().getStringExtra("id");
        vin = getIntent().getStringExtra("vin");
        loadingDialog = MyUtils.getLoadingDialog(mContext, false);

        newPartsParam = new NewPartsParam();
        newPartsParam.setCompanyId(MyUtils.getUser(mContext).getCompanyId());
        newPartsParam.setName(searching);
        newPartsParam.setPage(page);
        newPartsParam.setTypeId(id);

        View  emptyView = findViewById(R.id.emptyview);
        TextView go_special = emptyView.findViewById(R.id.go_special);
        go_special.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, SpecialBuyActivity.class);
                intent.putExtra("id", id);
                intent.putExtra("vin", vin);
                startActivity(intent);
            }
        });
        dataList.setEmptyView(emptyView);
        adapter = new IndicatorExpandableListAdapter(allDataList, allDataList);
        adapter.setCallback(this);
        dataList.setAdapter(adapter);

        AppApi.getNewPartsList(newPartsParam, this, 0, this);
        AppApi.getKind("0", "1", this, 1, this);
    }

    private void initSearch() {
        edSearch.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    // 先隐藏键盘
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(getCurrentFocus()
                                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    //进行搜索操作的方法，在该方法中可以加入mEditSearchUser的非空判断
                    if (edSearch.getText().toString().length() > 0) {
                        searching = edSearch.getText().toString();
                        loadingDialog.show();
                        page = 0;
                        newPartsParam.setPage(page);
                        newPartsParam.setName(searching);
                        AppApi.getNewPartsList(newPartsParam, NewChoosePartsActivity.this, 0, NewChoosePartsActivity.this);
                    } else {
                        Toast.makeText(mContext, "搜索关键字不能为空!", Toast.LENGTH_SHORT).show();
                    }
                }
                return false;
            }
        });
    }

    private void initRyc() {

        selectLl.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        selectAdapter = new PartsKindAdapter(R.layout.item_parts_select_kind, cList);
        selectLl.setAdapter(selectAdapter);
        selectAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                CheckBox checkBox = (CheckBox) view;
                if (checkBox.isChecked()) {
                    for (int i = 0; i < cList.size(); i++) {
                        if (position == i) {
                            cList.get(i).setCheck(true);
                        } else {
                            cList.get(i).setCheck(false);
                        }
                    }
                    loadingDialog.show();
                    typeId = cList.get(position).getId();
                    newPartsParam.setTypeId(typeId);
                    AppApi.getNewPartsList(newPartsParam, NewChoosePartsActivity.this, 0, NewChoosePartsActivity.this);
                }
                selectAdapter.notifyDataSetChanged();
            }
        });

        posRyc.setLayoutManager(new GridLayoutManager(mContext, 3));
        posAdapter = new PartsKindAdapter(R.layout.item_parts_kind, posList);
        posRyc.setAdapter(posAdapter);
        posAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                CheckBox checkBox = (CheckBox) view;
                if (checkBox.isChecked()) {
                    for (int i = 0; i < posList.size(); i++) {
                        if (position == i) {
                            posList.get(i).setCheck(true);
                        } else {
                            posList.get(i).setCheck(false);
                        }
                    }

                    if (cList.size() > 0) {
                        cList.clear();
                        pAdapter.notifyDataSetChanged();
                    }

                    loadingDialog.show();
                    AppApi.getKind(posList.get(position).getId(), "1", NewChoosePartsActivity.this, 2, NewChoosePartsActivity.this);
                }
                posAdapter.notifyDataSetChanged();
            }
        });

        pRyc.setLayoutManager(new GridLayoutManager(mContext, 3));
        pAdapter = new PartsKindAdapter(R.layout.item_parts_kind, pList);
        pRyc.setAdapter(pAdapter);
        pAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

                CheckBox checkBox = (CheckBox) view;
                if (checkBox.isChecked()) {
                    for (int i = 0; i < pList.size(); i++) {
                        if (position == i) {
                            pList.get(i).setCheck(true);
                        } else {
                            pList.get(i).setCheck(false);
                        }
                    }
                    loadingDialog.show();
                    typeId = pList.get(position).getId();
                    AppApi.getKind(pList.get(position).getId(), "1", NewChoosePartsActivity.this, 3, NewChoosePartsActivity.this);
                }
                pAdapter.notifyDataSetChanged();
            }
        });

        cRyc.setLayoutManager(new GridLayoutManager(mContext, 3));
        cAdapter = new PartsKindAdapter(R.layout.item_parts_kind, cList);
        cRyc.setAdapter(cAdapter);
        cAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                CheckBox checkBox = (CheckBox) view;
                if (checkBox.isChecked()) {
                    for (int i = 0; i < cList.size(); i++) {
                        if (position == i) {
                            cList.get(i).setCheck(true);
                        } else {
                            cList.get(i).setCheck(false);
                        }
                    }
                    typeId = cList.get(position).getId();
                }
                cAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public void clickTitle(int i) {
        super.clickTitle(i);
        switch (i) {
            case 1:
                finish();
                break;
        }
    }

    @Override
    public void handlerSuccessData(String result, int tag) {
        loadingDialog.cancelDialog();
        switch (tag) {
            case 0:
                showSuccess();
                NewPartsList newPartsList = JSON.parseObject(result, NewPartsList.class);
                List<NewPartsList.ResultListBean> dataBeanList = newPartsList.getResultList();
                if (page == 0) {
                    allDataList.clear();
                }

                for (NewPartsList.ResultListBean.PartsQualityListBean data : selectList) {
                    data.setGroupPos(-1);
                    data.setChildPos(-1);
                }

                for (int i = 0; i < dataBeanList.size(); i++) {
                    for (int k = 0; k < dataBeanList.get(i).getPartsQualityList().size(); k++) {
                        for (int j = 0; j < selectList.size(); j++) {
                            if (selectList.get(j).getCarWarehousePartsId().equals(dataBeanList.get(i).getPartsQualityList().get(k).getCarWarehousePartsId())) {
                                dataBeanList.get(i).getPartsQualityList().get(k).setWantCount(selectList.get(j).getWantCount());
                                selectList.get(j).setGroupPos(i);
                                selectList.get(j).setChildPos(k);
                                break;
                            }
                        }
                    }
                }

                Log.v("handlerSuccessData", JSON.toJSONString(dataBeanList));

                allDataList.addAll(dataBeanList);
                adapter.notifyDataSetChanged();
                break;
            case 1:
                posList.clear();
                KindList kindList = JSON.parseObject(result, KindList.class);
                List<KindList.ResultListBean> kindData = kindList.getResultList();
                posList.addAll(kindData);
                posAdapter.notifyDataSetChanged();
                break;
            case 2:
                pList.clear();
                KindList kindList2 = JSON.parseObject(result, KindList.class);
                List<KindList.ResultListBean> kindData2 = kindList2.getResultList();
                pList.addAll(kindData2);
                pAdapter.notifyDataSetChanged();
                break;
            case 3:
                cList.clear();
                KindList kindList3 = JSON.parseObject(result, KindList.class);
                List<KindList.ResultListBean> kindData3 = kindList3.getResultList();
                cList.addAll(kindData3);
                cAdapter.notifyDataSetChanged();
                break;
            case 4:
                break;
        }
    }

    @Override
    public void handlerFailData(String failString, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    public void handleErrorData(String error, int tag) {
        loadingDialog.cancelDialog();
    }

    private void initStateView() {
        if (simpleMultiStateView == null) return;
        simpleMultiStateView.setEmptyResource(R.layout.view_empty)
                .setRetryResource(R.layout.view_retry)
                .setLoadingResource(R.layout.view_loading)
                .setNoNetResource(R.layout.view_nonet)
                .build()
                .setonReLoadlistener(new MultiStateView.onReLoadlistener() {
                    @Override
                    public void onReload() {
                    }
                });
    }

    public void showLoading() {
        if (simpleMultiStateView != null) {
            simpleMultiStateView.showLoadingView();
        }
    }

    public void showSuccess() {
        if (simpleMultiStateView != null) {
            simpleMultiStateView.showContent();
        }
    }

    public void showFaild() {
        if (simpleMultiStateView != null) {
            simpleMultiStateView.showErrorView();
        }
    }

    public void showNoNet() {
        if (simpleMultiStateView != null) {
            simpleMultiStateView.showNoNetView();
        }
    }

    @Override
    public void count(int i, int groupPos, int childPos, NewPartsList.ResultListBean.PartsQualityListBean dataEntity) {
        selectList.size();
        NewPartsList.ResultListBean.PartsQualityListBean dataBean = new NewPartsList.ResultListBean.PartsQualityListBean();
        NewPartsList.ResultListBean.PartsQualityListBean entity;
        boolean isContain = false;
        if (groupPos == -1 || childPos == -1) {
            entity = dataEntity;
        } else {
            entity = allDataList.get(groupPos).getPartsQualityList().get(childPos);
            isContain = true;
        }
        switch (i) {
            case 1:
                if(isContain){
                    int wantCount1 = allDataList.get(groupPos).getPartsQualityList().get(childPos).getWantCount();
                    allDataList.get(groupPos).getPartsQualityList().get(childPos).setWantCount(wantCount1 + 1);
                    adapter.notifyDataSetChanged();
                }

                count++;
                dataBean.setEditPrice(entity.getEditPrice());
                dataBean.setWantCount(1);
                dataBean.setCount(count);
                dataBean.setGroupPos(groupPos);
                dataBean.setChildPos(childPos);
                dataBean.setCarWarehousePartsId(entity.getCarWarehousePartsId());
                dataBean.setOpen(entity.isOpen());
                dataBean.setPartsOeCode(entity.getPartsOeCode());
                dataBean.setPrice(entity.getPrice());
                dataBean.setPurchaseState(entity.getPurchaseState());
                dataBean.setQuality(entity.getQuality());
                dataBean.setPriceQx(entity.getPriceQx());
                dataBean.setWarehouseType(entity.getWarehouseType());
                dataBean.setPartsName(entity.getPartsName());
                addParts(dataBean);
                break;
            case 0:
                if(isContain){
                    int wantCount2 = allDataList.get(groupPos).getPartsQualityList().get(childPos).getWantCount();
                    allDataList.get(groupPos).getPartsQualityList().get(childPos).setWantCount(wantCount2 - 1);
                    adapter.notifyDataSetChanged();
                }
                count--;
                dataBean.setGroupPos(groupPos);
                dataBean.setChildPos(childPos);
                dataBean.setEditPrice(entity.getEditPrice());
                dataBean.setWantCount(1);
                dataBean.setCount(count);
                dataBean.setCarWarehousePartsId(entity.getCarWarehousePartsId());
                dataBean.setOpen(entity.isOpen());
                dataBean.setPartsOeCode(entity.getPartsOeCode());
                dataBean.setPrice(entity.getPrice());
                dataBean.setPurchaseState(entity.getPurchaseState());
                dataBean.setQuality(entity.getQuality());
                dataBean.setPriceQx(entity.getPriceQx());
                dataBean.setWarehouseType(entity.getWarehouseType());
                dataBean.setPartsName(entity.getPartsName());
                reduceParts(dataBean);
                break;
        }
        tvTip.setText("已选择" + count + "件");
    }

    private void addParts(NewPartsList.ResultListBean.PartsQualityListBean entity) {

        if (selectList.size() == 0) {
            selectList.add(entity);
        } else {
            boolean isContain = false;
            int pos = 0;

            for (int i = 0; i < selectList.size(); i++) {
                if (selectList.get(i).getCarWarehousePartsId().equals(entity.getCarWarehousePartsId())) {
                    isContain = true;
                    pos = i;
                    break;
                }
            }

            if (!isContain) {
                entity.setWantCount(1);
                selectList.add(entity);
            } else {
                int count = selectList.get(pos).getWantCount();
                selectList.get(pos).setWantCount(count + 1);
            }

        }

    }

    private void reduceParts(NewPartsList.ResultListBean.PartsQualityListBean entity) {
        int pos = 0;
        boolean iscontain = false;
        for (int i = 0; i < selectList.size(); i++) {
            if (selectList.get(i).getCarWarehousePartsId().equals(entity.getCarWarehousePartsId())) {
                pos = i;
                iscontain = true;
                break;
            }
        }

        if (iscontain) {
            int count = selectList.get(pos).getWantCount();
            if (count == 1) {
                selectList.remove(pos);
            } else {
                selectList.get(pos).setWantCount(count - 1);
            }
        }

    }

    @OnClick({R.id.special_btn, R.id.sure_select, R.id.tv_tip, R.id.sure, R.id.tv_filter})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.special_btn:
                Intent intent = new Intent(mContext, SpecialBuyActivity.class);
                intent.putExtra("id", id);
                intent.putExtra("vin", vin);
                startActivity(intent);
                break;
            case R.id.sure_select:
                selectAdapter.notifyDataSetChanged();
                dlLayout.closeDrawer(Gravity.END);
                page = 0;
                loadingDialog.show();
                newPartsParam.setTypeId(typeId);
                AppApi.getNewPartsList(newPartsParam, NewChoosePartsActivity.this, 0, NewChoosePartsActivity.this);
                break;
            case R.id.tv_tip:
                ArrayList<NewPartsList.ResultListBean.PartsQualityListBean> dataList = new ArrayList<>();
                dataList.addAll(selectList);
                bottomDataFragment = BottomDataFragment.newInstance(dataList);
                bottomDataFragment.setCallback(NewChoosePartsActivity.this);
                bottomDataFragment.show(getSupportFragmentManager(), R.id.bottomsheet);
                break;
            case R.id.sure:
                Intent sureintent = new Intent();
                sureintent.putParcelableArrayListExtra("data", selectList);
                setResult(RESULT_OK, sureintent);
                finish();
                break;
            case R.id.tv_filter:
                dlLayout.openDrawer(GravityCompat.END);
                break;
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.pos_radio:
                if (isChecked) {
                    AppApi.getKind("0", "1", this, 1, this);
                }
                break;
            case R.id.function_radio:
                if (isChecked) {
                    AppApi.getKind("1", "1", this, 1, this);
                }
                break;
        }
    }
}
